/*
	sqlengine.cpp

	Copyright (c) 2009 by Lms <lms.cze7@gmail.com>

 ***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************
*/

#include "sqliteengine.h"


SQLiteEngine::SQLiteEngine()
{
}

bool SQLiteEngine::connect(QString dbpath, QString connectionname)
{
	db = QSqlDatabase::addDatabase("QSQLITE", connectionname);
	db.setDatabaseName(dbpath);
	//qDebug()<<"[FMtune]"<<"-"<<dbpath;
	return (db.open());
}

void SQLiteEngine::close()
{
	db.close();
}

bool SQLiteEngine::TableExists(QString tablename)	 /* returns true if table exists in the database */
{  
	QString sql = "select [sql] from sqlite_master where [type] = 'table' and lower(name) = '" + tablename.toLower() + "'";
	QSqlQuery query(db);
	query.exec(sql);

	bool av;
	av = false;
	while (query.next()) {
		av = true;
	}
	return av;
}

bool SQLiteEngine::CreateTable(QString tablename, QStringList columns)
{
	if (!TableExists(tablename))
	{
		QString sql;
		QString scols = columns.join(", ");
		
		sql = "CREATE TABLE "+tablename+" ( "+scols+" )";
		qDebug()<<sql;

		QSqlQuery query(db);
		return (query.exec(sql));
	}
	else {	//table exists, check columns
		QStringList tableColumns;

		QString sql;		
		sql = "PRAGMA table_info("+tablename+")";

		QSqlQuery query(db);
		query.exec(sql);

		while (query.next()) {
			//qDebug()<<query.value(0).toString()<<query.value(1).toString()<<query.value(2).toString();
			tableColumns << query.value(1).toString();
		}

		int idx;
		for (int i = 0; i < columns.size(); ++i) {
			//qDebug()<<"COLUMN"<< getColumnName(columns[i]);
			idx=tableColumns.indexOf(getColumnName(columns[i]));
			if (idx==-1) {
				//qDebug()<<"not found"<<idx<<columns[i];
				//[TODO] Maybe without AFTER?
				sql="ALTER TABLE "+tablename+" ADD COLUMN "+columns[i]+" AFTER ["+getColumnName(columns[i-1])+"];";
				if (query.exec(sql)){
					qDebug()<<sql;
				}
				else {
					qDebug()<<"error;"<<sql;
				}
			}
		}

	}
}

QString SQLiteEngine::getColumnName(QString text)
{
	return text.mid( text.indexOf("[")+1, text.indexOf("]") - (text.indexOf("[")+1) );
}
